package com.hjq.demo.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;

import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.AppCompatTextView;

import com.hjq.bar.TitleBar;
import com.hjq.base.BaseDialog;
import com.hjq.demo.R;
import com.hjq.demo.aop.CheckNet;
import com.hjq.demo.aop.Log;
import com.hjq.demo.app.AppActivity;
import com.hjq.demo.http.api.AddShipmentApi;
import com.hjq.demo.http.api.DeleteShipmentApi;
import com.hjq.demo.http.api.ShipmentListApi;
import com.hjq.demo.http.api.UserListApi;
import com.hjq.demo.http.model.HttpData;
import com.hjq.demo.manager.InputTextManager;
import com.hjq.demo.other.DoubleUtils;
import com.hjq.demo.other.NewConfig;
import com.hjq.demo.ui.dialog.MenuDialog;
import com.hjq.demo.ui.dialog.MessageDialog;
import com.hjq.http.EasyHttp;
import com.hjq.http.EasyLog;
import com.hjq.http.listener.HttpCallback;
import com.hjq.widget.layout.SettingBar;
import com.hjq.widget.view.RegexEditText;

import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

//添加出货记录
public class AddShipmentRecordActivity extends AppActivity {
    private SettingBar sbPersonDataAccountCircle;
    private RegexEditText retCommodityNameInputHint;
    private RegexEditText retSpecificationNameInputHint;
    private RegexEditText retQuantityInputHint;
    private RegexEditText retUnitPriceInputHint;
    private AppCompatTextView retAmountInputHint;
    private RegexEditText retAmountPaidInputHint;
    private AppCompatTextView retUnpaidAmountInputHint;
    private RegexEditText retRemarksInputHint;
    private AppCompatButton btnShipmentRecordCommit;
    //看是新增是1          编辑3 默认新增
    private String isType = "1 ";
    //
    private String mSubType = "其他";
    private AppCompatButton abtAmount;
    private AppCompatButton abtUnpaidAmount;
    private LinearLayout llSpecificationNameInputHint;
    //出货记录 id
    private int id = 0;
    private SettingBar sbSpecificationUnit;
    @Override
    protected int getLayoutId() {
        return R.layout.activity_add_shipment_record;
    }

    private TitleBar tbShipmentRecord;

    @CheckNet
    @Log
    public static void start(Context context, String type, ShipmentListApi.Bean.RowsBean data) {
        if (TextUtils.isEmpty(type)) {
            return;
        }
        Intent intent = new Intent(context, AddShipmentRecordActivity.class);
        intent.putExtra(NewConfig.INTENT_JUMP_TYPE, type);
        //客户名称
        intent.putExtra("CustomerName", data.getUserId());
        //商品名称
        intent.putExtra("TradeName", data.getTradeName());
        //规格
        intent.putExtra("Specifications", data.getSpecs());
        //数量
        intent.putExtra("Quantity", data.getNumber());
        //单价
        intent.putExtra("UnitPrice", data.getUnitPrice());
        //总金额
        intent.putExtra("Amount", data.getSumOfMoney());
        //已付金额
        intent.putExtra("AmountPaid", data.getAmountPaid());
        //未付金额
        intent.putExtra("Unpaid", data.getUnpaidAmount());
        //备注
        intent.putExtra("Remarks", data.getRemark());
        intent.putExtra("ID", data.getId());
        intent.putExtra("subType", data.getSubType ());
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    @CheckNet
    @Log
    public static void start(Context context, String type) {
        if (TextUtils.isEmpty(type)) {
            return;
        }
        Intent intent = new Intent(context, AddShipmentRecordActivity.class);
        intent.putExtra(NewConfig.INTENT_JUMP_TYPE, type);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    @Override
    protected void initView() {
        sbPersonDataAccountCircle = (SettingBar) findViewById(R.id.sb_person_data_account_circle);
        retCommodityNameInputHint = (RegexEditText) findViewById(R.id.ret_commodity_name_input_hint);
        retSpecificationNameInputHint = (RegexEditText) findViewById(R.id.ret_specification_name_input_hint);
        retQuantityInputHint = (RegexEditText) findViewById(R.id.ret_quantity_input_hint);
        retUnitPriceInputHint = (RegexEditText) findViewById(R.id.ret_unit_price_input_hint);
        retAmountInputHint = (AppCompatTextView) findViewById(R.id.ret_amount_input_hint);
        retAmountPaidInputHint = (RegexEditText) findViewById(R.id.ret_amount_paid_input_hint);
        retUnpaidAmountInputHint = (AppCompatTextView) findViewById(R.id.ret_unpaid_amount_input_hint);
        retRemarksInputHint = (RegexEditText) findViewById(R.id.ret_remarks_input_hint);


        abtAmount = (AppCompatButton) findViewById(R.id.abt_amount);
        abtUnpaidAmount = (AppCompatButton) findViewById(R.id.abt_unpaid_amount);


        llSpecificationNameInputHint = (LinearLayout) findViewById(R.id.ll_specification_name_input_hint);

        sbSpecificationUnit = (SettingBar) findViewById(R.id.sb_specification_unit);


        tbShipmentRecord = (TitleBar) findViewById(R.id.tb_shipment_record);

        btnShipmentRecordCommit = (AppCompatButton) findViewById(R.id.btn_shipment_record_commit);
        InputTextManager.with(this)
                .addView(sbPersonDataAccountCircle.getRightView())
                .addView(retCommodityNameInputHint)
                .addView(sbSpecificationUnit.getRightView())
                .addView(retQuantityInputHint)
                .addView(retUnitPriceInputHint)
                .addView(retAmountInputHint)
                .addView(retAmountPaidInputHint)
                .addView(retUnpaidAmountInputHint)
                .setMain(btnShipmentRecordCommit)
                .build();
        setOnClickListener( abtAmount,abtUnpaidAmount,sbPersonDataAccountCircle,retCommodityNameInputHint,
                retSpecificationNameInputHint,
                retQuantityInputHint,
                retUnitPriceInputHint,
                retAmountInputHint,
                retAmountPaidInputHint,
                retUnpaidAmountInputHint,
                retRemarksInputHint,
                btnShipmentRecordCommit,sbSpecificationUnit);
    }

    @Override
    protected void initData() {
        isType = getString(NewConfig.INTENT_JUMP_TYPE);

        if (isType.equals("3")) {
//            //客户名称
//            intent.putExtra("CustomerName", data.getUserId());
//            //商品名称
//            intent.putExtra("TradeName", data.getTradeName());
//            //规格
//            intent.putExtra("Specifications", data.getSpecs());
//            //数量
//            intent.putExtra("Quantity", data.getNumber());
//            //单价
//            intent.putExtra("UnitPrice", data.getUnitPrice());
//            //总金额
//            intent.putExtra("Amount", data.getSumOfMoney());
//            //已付金额
//            intent.putExtra("AmountPaid", data.getAmountPaid());
//            //未付金额
//            intent.putExtra("Unpaid", data.getUnpaidAmount());
//            //备注
            mSubType = getString("subType");
            if (mSubType == null){
                mSubType ="其他 空"
                ;
            }
            if (mSubType.equals("米")){
                llSpecificationNameInputHint.setVisibility(View.VISIBLE);
                retSpecificationNameInputHint.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
            }else {
                llSpecificationNameInputHint.setVisibility(View.GONE);
            }
            tbShipmentRecord.setTitle("修改出货记录");
            tbShipmentRecord.setRightTitle("删除");
            tbShipmentRecord.setRightTitleColor(R.color.common_accent_color);
            sbPersonDataAccountCircle.setRightText(getString("CustomerName"));
            retCommodityNameInputHint.setText(getString("TradeName"));
            if (mSubType.contains("米")){
                retSpecificationNameInputHint.setText(getString("Specifications"));
            }
            retQuantityInputHint.setText(getString("Quantity"));
            retUnitPriceInputHint.setText(getDouble("UnitPrice")+ "");
            retAmountInputHint.setText(getDouble("Amount") + "");
            retAmountPaidInputHint.setText(getDouble("AmountPaid") + "");
            retUnpaidAmountInputHint.setText(getDouble("Unpaid") + "");
            retRemarksInputHint.setText(getString("Remarks"));
            id = getInt("ID");
            sbSpecificationUnit.setRightText(mSubType + getString("Specifications") );
        }
        sbSpecificationUnit.setRightText(mSubType  );
        initListener();
    }
    public void initListener(){
        //数量监听
        retQuantityInputHint.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                EasyLog.print("数量监听====>"+editable.toString().trim());
            }
        });
        //单价监听
        retUnitPriceInputHint.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                EasyLog.print("单价监听====>"+editable.toString().trim());

            }
        });
        //已付金额
        retAmountPaidInputHint.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                EasyLog.print("已付金额====>"+editable.toString().trim());

            }
        });
        //输入规格
        retSpecificationNameInputHint.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                EasyLog.print("输入规格====>"+editable.toString().trim());
                if (sbSpecificationUnit.getRightText().toString().contains("米")){
                    llSpecificationNameInputHint.setVisibility(View.VISIBLE);
                    retSpecificationNameInputHint.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
                }else {
                    llSpecificationNameInputHint.setVisibility(View.GONE);
                    retSpecificationNameInputHint.setInputType(InputType.TYPE_CLASS_TEXT);
                }

            }
        });
    }
    @Override
    public void onRightClick(View view) {
// 消息对话框
        new MessageDialog.Builder(getActivity())
                // 标题可以不用填写
                .setTitle("删除")
                // 内容必须要填写
                .setMessage("是否确认删除本次出货记录?")
                // 确定按钮文本
                .setConfirm(getString(R.string.common_confirm))
                // 设置 null 表示不显示取消按钮
                .setCancel(getString(R.string.common_cancel))
                // 设置点击按钮后不关闭对话框
                //.setAutoDismiss(false)
                .setListener(new MessageDialog.OnListener() {

                    @Override
                    public void onConfirm(BaseDialog dialog) {
                        DeleteShipmentHttp();
                    }

                    @Override
                    public void onCancel(BaseDialog dialog) {
                        toast("取消删除");
                    }
                })
                .show();
    }

    private void DeleteShipmentHttp() {
        EasyHttp.post(this)
                .api(new DeleteShipmentApi()
                        .setIds(id + "")
                )
                .request(new HttpCallback<HttpData<DeleteShipmentApi.Bean>>(this) {

                    @Override
                    public void onSucceed(HttpData<DeleteShipmentApi.Bean> data) {
                        //编辑完成
                        toast(R.string.common_edit_complete);
                        finish();
                    }

                    @Override
                    public void onFail(Exception e) {
                        super.onFail(e);
                        toast(R.string.common_edit_error);
                    }
                });

    }


    @Override
    public void onClick(View view) {
        if (view == btnShipmentRecordCommit) {
            if (sbSpecificationUnit.getRightText().toString().contains("米") &&  retSpecificationNameInputHint.getText().toString().isEmpty()){
                toast("规格米没有填入数据");
                return;
            }
            // 消息对话框
            new MessageDialog.Builder(getActivity())
                    // 标题可以不用填写
                    .setTitle("提醒")
                    // 内容必须要填写
                    .setMessage("确认已经计算过了?")
                    // 确定按钮文本
                    .setConfirm("确认")
                    // 设置 null 表示不显示取消按钮
                    .setCancel("呀，我忘了！")
                    // 设置点击按钮后不关闭对话框
                    //.setAutoDismiss(false)
                    .setListener(new MessageDialog.OnListener() {

                        @Override
                        public void onConfirm(BaseDialog dialo) {
                            CommidData();
                        }
                        @Override
                        public void onCancel(BaseDialog dialog) {

                        }
                    })
                    .show();


            return;
        } else if (view == abtAmount) {
            if (sbSpecificationUnit.getRightText().toString().contains("米") &&  retSpecificationNameInputHint.getText().toString().isEmpty()){
                toast("规格米没有填入数据哟!");
                return;
            }
            //总金额点击计算
            TotalAmountCalculation();
            return;
        } else if (view == abtUnpaidAmount) {
            //未付金额点击计算
            UnpaidTotalAmountCalculation();

        } else if (view == retUnitPriceInputHint) {
            //单价
            return;

        } else if (view == retAmountInputHint) {
            //总金额

            return;
        } else if (view == retAmountPaidInputHint) {
            //已付金额
            return;

        } else if (view == retUnpaidAmountInputHint) {
            //未付金额

            return;
        } else if (view == retRemarksInputHint) {
            //备注

            return;
        } else if (view == sbSpecificationUnit) {
            //选择规格
            /**
             * 模拟数据
             */
            //居中选择框
            List<String> dataName = new ArrayList<>();
            dataName.add("米");
            dataName.add("张");
            dataName.add("盒");
            dataName.add("根");
            dataName.add("捆");
            dataName.add("其他");
            new MenuDialog.Builder(getContext())
                    .setGravity(Gravity.CENTER)
                    // 设置 null 表示不显示取消按钮
                    //.setCancel(null)
                    // 设置点击按钮后不关闭对话框
                    //.setAutoDismiss(false)
                    .setList(dataName)
                    .setListener(new MenuDialog.OnListener<String>() {
                        @Override
                        public void onSelected(BaseDialog dialog, int position, String string) {
                            sbSpecificationUnit.setRightText(string);
                            mSubType= string;
                            if (string.equals("米")){
                                llSpecificationNameInputHint.setVisibility(View.VISIBLE);
                                retSpecificationNameInputHint.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
                            }else {
                                llSpecificationNameInputHint.setVisibility(View.GONE);
                                retSpecificationNameInputHint.setInputType(InputType.TYPE_CLASS_TEXT);
                            }
                        }
                        @Override
                        public void onCancel(BaseDialog dialog) {
                            toast("取消了");
                        }
                    })
                    .show();
            return;
        }  else if (view == sbPersonDataAccountCircle) {
            analogData();
            return;
        }


    }

    //客户名称data
    private void analogData() {
        EasyHttp.get(this)
                .api(new UserListApi().setPageSize("100")
                        .setPageNum("1"))
                .request(new HttpCallback<HttpData<UserListApi.Bean>>(this) {

                    @Override
                    public void onSucceed(HttpData<UserListApi.Bean> data) {
                        int dataNameSize = data.getData().getRows().size();
                        //居中选择框
                        List<String> dataName = new ArrayList<>();
                        for (int i = 0; i < dataNameSize; i++) {
                            dataName.add(data.getData().getRows().get(i).getUsername());
                        }
                        /**
                         * 模拟数据
                         */
                        new MenuDialog.Builder(getContext())
                                .setGravity(Gravity.CENTER)
                                // 设置 null 表示不显示取消按钮
                                //.setCancel(null)
                                // 设置点击按钮后不关闭对话框
                                //.setAutoDismiss(false)
                                .setList(dataName)
                                .setListener(new MenuDialog.OnListener<String>() {
                                    @Override
                                    public void onSelected(BaseDialog dialog, int position, String string) {
                                        sbPersonDataAccountCircle.setRightText(string);
                                    }

                                    @Override
                                    public void onCancel(BaseDialog dialog) {
                                        toast("取消了");
                                    }
                                })
                                .show();
                    }

                    @Override
                    public void onFail(Exception e) {
                        super.onFail(e);
                    }
                });

    }

//判断整数（int）
    private boolean isInteger(String str) {
        if (null == str || "".equals(str)) {
            return false;
        }
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }

    //判断浮点数（double和float）
    private boolean isDouble(String str) {
        if (null == str || "".equals(str)) {
            return false;
        }
        Pattern pattern = Pattern.compile("^[-\\+]?\\d*[.]\\d+$"); // 之前这里正则表达式错误，现更正
        return pattern.matcher(str).matches();
    }
    //判断首位是否为0
    public boolean isNumericFirstShow(String str){
        if (str.substring(0,1).equals("0")){
            return true;
        }else {
            return false;
        }
    }

    //判断长度是否大于0
    public boolean isNumericFirstLength(String str){
        if (str.length() > 0){
            return true;
        }else {
            return false;
        }
    }

    //总金额计算
    public void TotalAmountCalculation(){
        //数量
        String  mQuantityString  =   retQuantityInputHint.getText().toString();
        //单价
        String  mUnitPriceString  =    retUnitPriceInputHint.getText().toString();
        //规格
        String  mSpecificationNameInputHint  =    retSpecificationNameInputHint.getText().toString();
        if (!isInteger(mQuantityString)){
            toast("数量不是整数请检查");
            return;
        }
        if (!isDouble(mUnitPriceString)){
            toast("单价不是全部小数请检查");
            return;
        }
        if (!isNumericFirstLength(mQuantityString)){
            toast("数量长度小于0请检查");
            return;
        }
        if (!isNumericFirstLength(mUnitPriceString)){
            toast("单价长度小于0请检查");
            return;
        }
        if (isNumericFirstShow(mQuantityString)){
            toast("数量首位为0请检查");
            return;
        }
        if (isNumericFirstShow(mUnitPriceString)){
            toast("单价首位为0数字请检查");
            return;
        }

        //数量
        Double mDoubleQuantityString=      Double.parseDouble(mQuantityString);
        //单价
        Double  mDoubleUnitPriceString= Double.parseDouble(mUnitPriceString);
        // 总金额
        Double TotalAmount ;
        if (sbSpecificationUnit.getRightText().toString().equals("米") ){
            //规格
            Double mDoubleSpecificationNameInputHint =  Double.parseDouble(mSpecificationNameInputHint);
            if (!isNumericFirstLength(mSpecificationNameInputHint)){
                toast("规格长度小于0请检查");
                return;
            }
            if (!isDouble(mSpecificationNameInputHint)){
                toast("规格不是全部小数请检查");
                return;
            }
            if (isNumericFirstShow(mSpecificationNameInputHint)){
                toast("规格首位为0数字请检查");
                return;
            }
            //计算数量与单价,规格 相乘
            TotalAmount = DoubleUtils.mul(DoubleUtils.mul(mDoubleQuantityString,mDoubleUnitPriceString),mDoubleSpecificationNameInputHint);
        }else {
            //计算数量与单价相乘
            TotalAmount = DoubleUtils.mul(mDoubleQuantityString,mDoubleUnitPriceString);
        }
        retAmountInputHint.setText(TotalAmount+"");
    }
    //未付金额计算
    public void UnpaidTotalAmountCalculation(){
        //已付金额
        String  mAmountPaidInputHintString  =    retAmountPaidInputHint.getText().toString();
        //总金额
        String  mAmountInputHintString  =    retAmountInputHint.getText().toString();
        if (!isNumericFirstLength(mAmountInputHintString)){
            toast("总金额长度小于0请检查");
            return;
        }
        if (isNumericFirstShow(mAmountInputHintString)){
            toast("总金额首位为0请检查");
            return;
        }
        //已付金额
        Double mDoubleAmountPaidInputHintString=  Double.parseDouble(mAmountPaidInputHintString);
        // 总金额
        Double TotalAmount = Double.parseDouble(mAmountInputHintString);
        if (mDoubleAmountPaidInputHintString > TotalAmount){
            toast("已付金额 大于 总金额 请从新输入");
            return;
        }
        //未付金额
        Double UnpaidAmount = DoubleUtils.sub(TotalAmount,mDoubleAmountPaidInputHintString);
        retUnpaidAmountInputHint.setText(UnpaidAmount+"");
    }

    public void CommidData(){
        //完成
        if (isType.equals("3")) {
            //编辑
            EasyHttp.put(this)
                    .api(new AddShipmentApi()
                            .setId(id+"")
                            .setSubType(mSubType)
                            .setUserId(sbPersonDataAccountCircle.getRightText().toString())
                            .setTradeName(retCommodityNameInputHint.getText().toString())
                            .setSpecs(mSubType)
                            .setNumber(retQuantityInputHint.getText().toString())
                            .setUnitPrice(retUnitPriceInputHint.getText().toString())
                            .setSumOfMoney(retAmountInputHint.getText().toString())
                            .setAmountPaid(retAmountPaidInputHint.getText().toString())
                            .setUnpaidAmount(retUnpaidAmountInputHint.getText().toString())
                            .setRemark(retRemarksInputHint.getText().toString())
                    )
                    .request(new HttpCallback<HttpData<AddShipmentApi.Bean>>(this) {

                        @Override
                        public void onSucceed(HttpData<AddShipmentApi.Bean> data) {
                            toast(R.string.common_edit_complete);
                            finish();
                        }

                        @Override
                        public void onFail(Exception e) {
                            super.onFail(e);
                            toast(R.string.common_edit_error);
                        }
                    });
            return;
        } else if (isType.equals("1")) {
            //添加完成
            EasyHttp.post(this)
                    .api(new AddShipmentApi()
                            .setSubType(mSubType)
                            .setUserId(sbPersonDataAccountCircle.getRightText().toString())
                            .setTradeName(retCommodityNameInputHint.getText().toString())
                            .setSpecs(retSpecificationNameInputHint.getText().toString())
                            .setNumber(retQuantityInputHint.getText().toString())
                            .setUnitPrice(retUnitPriceInputHint.getText().toString())
                            .setSumOfMoney(retAmountInputHint.getText().toString())
                            .setAmountPaid(retAmountPaidInputHint.getText().toString())
                            .setUnpaidAmount(retUnpaidAmountInputHint.getText().toString())
                            .setRemark(retRemarksInputHint.getText().toString())
                    )
                    .request(new HttpCallback<HttpData<AddShipmentApi.Bean>>(this) {

                        @Override
                        public void onSucceed(HttpData<AddShipmentApi.Bean> data) {
                            toast(R.string.common_add_complete);
                            finish();
                        }

                        @Override
                        public void onFail(Exception e) {
                            super.onFail(e);
                            toast(R.string.common_add_error);
                        }
                    });
            return;
        }
    }

}